var SID_URL = 'http://vod.moretv.com.cn/Service/Program?callback=?';
var SEARCH_URL = 'http://search.moretv.com.cn/fullSearch?pageSize=12&callback=?';
var AUTHENTICATE_URL = 'http://api.moretv.com.cn/web/client?callback=?';
var UpLogUrl = 'http://mobilelog.moretv.com.cn/weixin?callback=?';
var Version = '0.1';
var CHNNEL_LIST_URL='http://vod.moretv.com.cn/Service/findChannelGroup?callback=?';
var CHNNEL_CURRENT_LIST_URL='http://vod.moretv.com.cn/Service/findCurrentChannelItem?callback=?';
var CHNNEL_PROGRAMS_LIST_URL='http://vod.moretv.com.cn/Service/findTVChannelItem?version=2&pre=1&callback=?';
var PERSON_DETAIL_URL = 'http://search.moretv.com.cn/person/';
var CONTAINER_FEED_URL = 'http://vod.moretv.com.cn/Service/container?token=xxxx&callback=?';

var TYPE_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?type=0&callback=?&token=xxx';//type=0
//var TYPE_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?contentType=movie&code=xxx&pageSize=12&pageIndex=1&type=0';//type=0
var AREA_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?type=1&callback=?&token=xxx';//type=1
//var AREA_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?contentType=movie&code=xxx&pageSize=12&pageIndex=1&type=1';//type=1
var SEARCH_FEED_URL = 'http://vod.moretv.com.cn/Service/KeyWords?callback=?&token=xxx';//type=2
//var SEARCH_FEED_URL = 'http://vod.moretv.com.cn/Service/KeyWords?callback=jsonp1378611777850&contentType=movie';//type=2
var HOT_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?type=3&callback=?&token=xxx';//type=3
//var HOT_FEED_URL = 'http://vod.moretv.com.cn/Service/queryPrograms?contentType=movie&code=xxx&pageSize=12&pageIndex=1&type=3';//type=3
var CONTAINER_FEED_URL = 'http://vod.moretv.com.cn/Service/container?callback=?&token=xxx';//type=4
//var CONTAINER_FEED_URL = 'http://vod.moretv.com.cn/Service/container?code=xxxx&pageSize=10&pageIndex=1';//type=4
var GUESS_FEED_URL = 'http://vod.moretv.com.cn/Service/ContenTypeRecommendation?contentType=movie/tv&userId=4ca10be30f8f6245a565ba3f3ee5d312&pageSize=12&pageIndex=1';//type=5
var MULTI_SEARCH_FEED_URL = 'http://vod.moretv.com.cn/Service/multiSearch?token=xx&contentType=movie&pageSize=12&sort=hot&tag=all&area=all&year=all';//type=6
var ALBUM_LIST_URL = 'http://vod.moretv.com.cn/Service/Subject?callback=?';
var MULTI_SEARCH_CONDITION_URL = 'http://vod.moretv.com.cn/Service/getMultiParams4.jsp?callback=?';
var MULTI_SEARCH_URL = 'http://vod.moretv.com.cn/Service/multiSearch?callback=?&token=xx';
var MULTI_SEARCH_HOT_URL ='http://vod.moretv.com.cn/Service/container?callback=?'
var WeChatHelperConstants = {
    ContentType:{
        MOVIE:'movie',
        TV:'tv',
        ZONGYI:'zongyi',
        SHORTVIDEO:'hot',
        KIDS:'kids',
        COMIC:'comic',
        HISTORY:'history',
        MV:'mv',
        JILU:'jilu',
        XIQU:'xiqu',
        SPORTS:'sports',
        ALL:'all',
        LIVE:'live',
        CAST:'cast',
        OTHERS:'others'
    },
    HotPlayUrl :'hot_play.html',
    CommonAjaxTimeStamp:0,
    SelectAnthologyTermPageValueArr:[[]],
    CurrentInfoRes : null,
    SearchPageCapacity : 12,
    SearchValues:{},
    SearchKey:'',
    SearchCurrentPageIndex:1,
    AnthologyCurrentPageIndex:1,
    AnthologyScrollLine:0,
    FindCurrentEpisode : false,
    CommonAjaxTimer : null,
    CommonAjaxTimeout:5000,
    TotalSecond:0,
    PlayingStatus:7,
    PauseStatus:8,
    WeChatOperate : {
        play : 1,
        pause : 2,
        seek : 3,
        volume : 4,
        stop : 5,
        direct : 6,
        show : 7
    },
    Action : {
        Play : 'wxPlay',
        PlayControl : 'wxPlayControl',
        Connect : 'wxConnect',
        Event : 'event'
    },
    EventType : {
        StartApp : 1,
        MobileRemoteControl : 100,
        PinEnterPlay : 200,
        Connect : 300,
        Play : 400,
        AddDevice : 500,
        ChangeDevice : 600,
        GetCurrentDevice : 700
    },
    CurrentEventType : 400,
    CurrentDeviceObj : null,
    DirectKey : 'keyName',
    DirectValue : {
        Left : 'Left',
        Right : 'Right',
        Up : 'Up',
        Down : 'Down',
        Enter : 'Enter',
        Home : 'Home',
        Esc : 'Esc',
        Menu : 'Menu',
        VolumeZoom : 'VolumeZoom',
        VolumeReduce : 'VolumeReduce'
    },
    Loading : false,
    DetailpSid : '',
    DetailsSid : '',
    DetailContentType : '',
    DetailPlayType : 1,
    PrevVolumeTop : 0,
    LogType : {
        Search : 'search',
        Live : 'live',
        SubScription : 'subScription',
        RemoteControl : 'remoteControl',
        Play : 'play',
        Album : 'album'
    },
    DetailPageFrom : {
        Search : 'index',
        MySubScription : 'mySubScription',
        SubScriptionMore : 'subScriptionMore',
        AlbumList : 'albumList',
        WeiXinSearch : 'weiXinSearch',
        WeiXinRecommend : 'weiXinRecommend',
        Filter:'filter'
    },
    RandomUserNamePrefix : '{rad}-',
    WeiXinJSBridge : null,
    DefaultImgBgType : {
        ChannelIcon : 1,
        Person : 2,
        LargeProgram : 3,
        SmallProgram : 4,
        SubScriptionIcon : 5
    },
    SubScriptionObj : [],//已订阅标签对象  对象结构：{groupCode:groupCode,code:code,type:type,contentType:contentType,templateCode:templateCode,title:title}
    SubScriptionTree : [],//订阅数缓存，对象数组，对象结构：{groupName:groupName,groupContentType:groupContentType,items:[{itemName:itemName,itemCode:itemCode,itemType:itemType,itemIcon1:itemIcon1,itemTemplateCode:itemTemplateCode,itemContentType:itemContentType}]}
    PlayType : {
        LargeProgram:1,
        SmallProgram:2,
        Live:3,
        Local:4
    },
    LogPlayType : {
        LivePlay : 'livePlay',
        LocalPlay : 'localPlay',
        RecommendPlay : 'recommendPlay',
        SubScriptionPlay : 'subScriptionPlay',
        SearchPlay : 'searchPlay',
        AlbumPlay : 'albumPlay'
    },
    longImgHeightCookieKey : 'longImgHeightCookieKey',
    shortImgHeightCookieKey : 'shortImgHeightCookieKey',
    headerHeightCookieKey : 'headerHeightCookieKey',
    scrollTopKey : 'scrollTopKey',
    timer1:null,
    timeout1:5000,
    timer2:null,
    timeout2:5000,
    timer3:null,
    timeout3:5000,
    timer4:null,
    timeout4:5000,
    timer5:null,
    timeout5:5000,
    timer6:null,
    timeout6:5000,
    RedirectFrom : {
        PortalPage : 'portal_page',
        EditorRecommend : 'editor_recommend',
        WeinXinClient : 'weixin_client'
    },
    timeout_flag1 : true,
    timeout_flag2 : true,
    timeout_flag_o : true,
    timeout_flag_timer1_o : null,
    timeout_flag_timer2_o : null,
    timeout_flag_timer3_o : null,
    timeout_flag_timeout1_o : 5000,
    timeout_flag_timeout2_o : 5000,
    timeout_flag_timeout3_o : 5000,


    status_flag1 : false,
    status_flag2 : false,
    PlayUrls : null



};



var ConnectDeviceFlag = false;
var ConnectDeviceFlagLocalKey = 'connectDeviceFlag';
var CurrentDeviceIdLocalKey = 'currentDeviceId';
var CurrentDeviceLocalKey = 'currentDevice';
var DevicesLocalKey = 'devices';
var CurrentAccountLocalKey = 'currentAccount';
var AccountDevicesLocalKeyPrefix = 'accountDevices-';
//全局timer默认初始值，该值固定不可变，方便初始化全局timer使用
var globalTimerDefault = {
    connectAuthorTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    connectDeviceTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playVideoTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playControlTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    submitResultTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    getDataTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    getAccessTokenTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    setWXUserInfoToAppTimer : {timer:null,timeout:3000,retry:3,count:0,timeoutFlag:true,executeTimeoutFun:false},
    intervalTimer : {timer:null,timeout:2000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    sysTimeTimer : {timer:null,timeout:1000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playImageTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false}
};
//全局timer，该值随时可能变化，要置为初始值时使用globalTimerDefault赋值；er：globalTimer.connectAuthorTimer = globalTimerDefault.connectAuthorTimer
var globalTimer = {
    connectAuthorTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    connectDeviceTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playVideoTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playControlTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    submitResultTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    getDataTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    getAccessTokenTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    setWXUserInfoToAppTimer : {timer:null,timeout:3000,retry:3,count:0,timeoutFlag:true,executeTimeoutFun:false},
    intervalTimer : {timer:null,timeout:2000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    sysTimeTimer : {timer:null,timeout:1000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false},
    playImageTimer : {timer:null,timeout:3000,retry:0,count:0,timeoutFlag:true,executeTimeoutFun:false}
};
var Log = {
    Info : {type:1,prefix:'MoreTV WeinXin ~ Info: '},
    Debug : {type:2,prefix:'MoreTV WeinXin ~ Debug: '},
    Error : {type:3,prefix:'MoreTV WeinXin ~ Error: '}
};
var Action = {
    Event: 'event'
};
var EventType = {
    StartApp : 1,
    MobileRemoteControl : 100,
    DanMuControl : 103,
    WeiXinControl : 104,
    SpeakControl : 105,
    PinEnterPlay : 200,
    Connect : 300,
    VideoPlay : 101,
    ImagePlay : 102,
    AddDevice : 500,
    ChangeDevice : 600,
    GetCurrentDevice : 700
};
var ParamsAction = {
    Play : 0,
    transfer : 'transfer'
};
var ParamsValue = {
    refreshPage : 'refresh'
};
var ParamsKey = {
    danMuComments : 'danmuComment',
    danMuPlayInfo : 'danmuPlayInfo',
    weiXinUserInfo : 'userInfo',
    danmuPushPlay : 'danmuPushPLAY'
};
var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }()
};

function getUrlParams(){
    var urlParams = {};
    var urlSearch=location.search;
    if (urlSearch.indexOf("?") == 0 && urlSearch.indexOf("=")>1){
        var arrSource = unescape(urlSearch).substring(1,urlSearch.length).split("&");
        for(var i=0;i<arrSource.length;i++){
            var arrName=arrSource[i].split("=");
            urlParams[arrName[0]] = arrName[1];
        }
    }
    return urlParams;
};
function loadImg(imgLi,bg){
    if(imgLi && imgLi.length>0){
        for (var i = 0; i < imgLi.length; i++){
            var theImg = imgLi[i];
            if(theImg.getAttribute('url')!=''&&theImg.getAttribute('url')!='undefined'){
                var theUrl=theImg.getAttribute('url');
                imgReady(theImg,theUrl,function(){},function(imgs,width,heights){// 加载完成事件
                },function(){
                    theImg.src=bg;
                    console.log("图片加载错误");
                });
            }else{
                //theImg.src=bg;
                console.log("没有图片地址");
            }
        }
    }else{
        console.log("需要加载的图片集合不存在~");
    }
};
var imgReady = (function () {
    var list = [], intervalId = null,
    // 用来执行队列
        tick = function () {
            var i = 0;
            for (; i < list.length; i++) {
                list[i].end ? list.splice(i--, 1) : list[i]();
            };
            !list.length && stop();
        },
    // 停止所有定时器队列
        stop = function () {
            clearInterval(intervalId);
            intervalId = null;
        };
    return function(imgs,url, ready, load, error) {
        var onready, width, height, newWidth, newHeight,
            img = new Image();
        img.src = url;
        // 如果图片被缓存，则直接返回缓存数据
//		if (img.complete) {
//			ready.call(img);
//			load && load.call(img);
//			return;
//		};
        // 加载错误后的事件
        img.onerror = function () {
            error && error.call(img);
            onready.end = true;
        };
        // 图片尺寸就绪
        onready = function () {
            newWidth = img.width;
            newHeight = img.height;
            if (newWidth !== width || newHeight !== height ||
                // 如果图片已经在其他地方加载可使用面积检测
                newWidth * newHeight > 1024
                ) {
                ready.call(img);
                onready.end = true;
            };
        };
        onready();
        // 完全加载完毕的事件
        img.onload = function () {
            width = img.width;
            height = img.height;
            // onload在定时器时间差范围内可能比onready快
            // 这里进行检查并保证onready优先执行
            !onready.end && onready();
            load && load(imgs,width,height);
            // IE gif动画会循环执行onload，置空onload即可
            img = img.onload = img.onerror = null;
            imgs.src=url;
        };
        // 加入队列中定期执行
        if (!onready.end) {
            list.push(onready);
            // 无论何时只允许出现一个定时器，减少浏览器性能损耗
            if (intervalId === null) intervalId = setInterval(tick, 40);
        };
    };
})();
function commonAjax(url, data, callback,type) {
    if(type){
        type="POST";
    }else{
        type="GET";
    }
    var timestamp = +new Date();
    WeChatHelperConstants.CommonAjaxTimeStamp = timestamp;
    $.ajax({
        type: type,
        url:url,
        data:data,
        dataType:'json',
        context:timestamp,
        cache:true,
        success:callback
    });
};
function commonAjaxForUpLog(url, data, callback,type) {
    if(type){
        type="POST";
    }else{
        type="GET";
    }
    $.ajax({
        type: type,
        url:url,
        data:data,
        dataType:'jsonp',
        cache:true,
        success:callback
    });
};
function secondToTimeFormat(seconds){
    if (typeof seconds == 'undefined' || !seconds){
        return '未知';
    }
    var hours = parseInt(seconds / (60*60));
    var minutes  = parseInt((seconds-(hours*60*60)) / 60);
    var second = parseInt(seconds-(hours*60*60) - minutes*60);
    minutes = minutes < 10 ? '0'+minutes : minutes;
    second = second < 10 ? '0'+second : second;
    return  hours + ":" + minutes + ":" + second;
};
function secondToTimeFormat2(seconds){
    if (typeof seconds == 'undefined' || !seconds){
        return '00:00';
    }
    var minutes  = parseInt(seconds / 60);
    var second = parseInt(seconds-minutes*60);
    minutes = minutes < 10 ? '0'+minutes : minutes;
    second = second < 10 ? '0'+second : second;
    return minutes + ":" + second;
};
function secondToTimeFormat3(seconds){
    if (typeof seconds == 'undefined' || !seconds){
        return ['00','00','00'];
    }
    var hours = parseInt(seconds / (60*60));
    var minutes  = parseInt((seconds-(hours*60*60)) / 60);
    var second = parseInt(seconds-(hours*60*60) - minutes*60);
    hours = hours < 10 ? '0' + hours : hours ;
    minutes = minutes < 10 ? '0'+minutes : minutes;
    second = second < 10 ? '0'+second : second;
    return  [hours,minutes,second];
};
function getDateDiff(dateTime) {
    var result = '';
    var second = 1000;
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var now = new Date().getTime()+1;
    var diffValue = now - parseInt(dateTime,10);
    var dayTemp = Math.round(diffValue / day);
    var hourTemp = Math.round(diffValue / hour);
    var minTemp = Math.round(diffValue / minute);
    var secTemp = Math.round(diffValue / second);
    if (dayTemp >= 1) {
        result =  dayTemp+'天前';
    }else if (hourTemp >= 1) {
        result =  hourTemp+'小时前';
    }else if (minTemp >= 1) {
        result = minTemp + '分钟前';
    }else if(secTemp >= 1){
        result = secTemp+"秒前";
    }else{
        result = '刚刚';
    }
    return result;
};
/********************
 * 取窗口滚动条高度
 ******************/
function getScrollTop() {
    var scrollTop = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    return scrollTop;
}


/********************
 * 取窗口可视范围的高度
 *******************/
function getClientHeight() {
    var clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        var clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    else {
        var clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
}

/********************
 * 取文档内容实际高度
 *******************/
function getScrollHeight() {
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}


/**
 *
 *  Base64 encode / decode
 *
 *  @author haitao.tu
 *  @date   2010-04-26
 *  @email  tuhaitao@foxmail.com
 *
 */

function Base64() {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}


(function(window,doc) {
    var thatVar;
    touchControler = function(ele,opt){
        thatVar = this;
        var that = this;
        that.scroller = doc.getElementById(ele);
        that.options = {
            direction:'H',
            value:100,
            radius:10,
            offsetPosition:0,
            range:100,
            startCallBack:null,
            moveCallBack:null,
            endCallBack:null
        };
        for (var i in opt) that.options[i] = opt[i];
        that.options.id = ele;
        that.scroller.addEventListener('click',that.touchStart,false);
        that.scroller.addEventListener('touchmove',that.touchMove,false);
        that.scroller.addEventListener('touchend',that.touchEnd,false);
    };
    touchControler.prototype = {
        currentValue : 0,
        touchStart : function(e){
            e.preventDefault();
            var that = thatVar;
//            if(this.options.startCallBack){
//                this.options.startCallBack();
//            }
        },
        touchMove:function (e) {
            e.preventDefault();
            var that = thatVar;
            var opt = that.options;
            alert(opt);
            alert(opt.id);
            var point = e.touches[0];
            switch (opt.direction) {
                case 'H':
                    var minL = 0;
                    var maxL = opt.range - 2 * opt.radius;
                    var cL = parseInt($('#'+opt.id).css('left'));
                    alert(maxL);
                    if (cL >= minL && cL <= maxL) {
                        var nL = point.pageX - opt.offsetPosition;
                        $('#'+opt.id).css('left', nL + 'px');
                    }
                    var mL = maxL - minL;
                    that.currentValue = opt.value*(nL/mL);
                    break;
                case 'V':
                    var minT = 0;
                    var maxT = opt.range - 2* opt.radius;
                    var cT = parseInt($('#'+opt.id).css('top'));
                    if(cT >= minT && cT <= maxT){
                        var nT = point.pageY - opt.offsetPosition;
                        $('#'+opt.id).css('top', nT + 'px');
                    }
                    var mT = maxT - minT;
                    that.currentValue = opt.value*(nT/mT);
                    break;
            };
//            if(that.options.moveCallBack){
//                that.options.moveCallBack();
//            }
        },
        touchEnd : function(e){
            e.preventDefault();
            var that = thatVar;
            if(that.options.endCallBack){
                that.options.endCallBack();
            }
        }
    };
    window.touchControler = touchControler;
})(window,document);
/*!
 Math.uuid.js (v1.4)
 http://www.broofa.com
 mailto:robert@broofa.com

 Copyright (c) 2010 Robert Kieffer
 Dual licensed under the MIT and GPL licenses.
 */

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
(function() {
    // Private array of chars to use
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

    Math.uuid = function (len, radix) {
        var chars = CHARS, uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random()*16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    };

    // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
    // by minimizing calls to random()
    Math.uuidFast = function() {
        var chars = CHARS, uuid = new Array(36), rnd=0, r;
        for (var i = 0; i < 36; i++) {
            if (i==8 || i==13 ||  i==18 || i==23) {
                uuid[i] = '-';
            } else if (i==14) {
                uuid[i] = '4';
            } else {
                if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
                r = rnd & 0xf;
                rnd = rnd >> 4;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
        return uuid.join('');
    };

    // A more compact, but less performant, RFC4122v4 solution:
    Math.uuidCompact = function() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    };
})();
/*
 函数：格式化日期
 参数：formatStr-格式化字符串
 d：将日显示为不带前导零的数字，如1
 dd：将日显示为带前导零的数字，如01
 ddd：将日显示为缩写形式，如Sun
 dddd：将日显示为全名，如Sunday
 M：将月份显示为不带前导零的数字，如一月显示为1
 MM：将月份显示为带前导零的数字，如01
 MMM：将月份显示为缩写形式，如Jan
 MMMM：将月份显示为完整月份名，如January
 yy：以两位数字格式显示年份
 yyyy：以四位数字格式显示年份
 h：使用12小时制将小时显示为不带前导零的数字，注意||的用法
 hh：使用12小时制将小时显示为带前导零的数字
 H：使用24小时制将小时显示为不带前导零的数字
 HH：使用24小时制将小时显示为带前导零的数字
 m：将分钟显示为不带前导零的数字
 mm：将分钟显示为带前导零的数字
 s：将秒显示为不带前导零的数字
 ss：将秒显示为带前导零的数字
 l：将毫秒显示为不带前导零的数字
 ll：将毫秒显示为带前导零的数字
 tt：显示am/pm
 TT：显示AM/PM
 返回：格式化后的日期
 */
Date.prototype.format = function (formatStr) {
    var date = this;
    /*
     函数：填充0字符
     参数：value-需要填充的字符串, length-总长度
     返回：填充后的字符串
     */
    var zeroize = function (value, length) {
        if (!length) {
            length = 2;
        }
        value = new String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++) {
            zeros += '0';
        }
        return zeros + value;
    };
    return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function($0) {
        switch ($0) {
            case 'd': return date.getDate();
            case 'dd': return zeroize(date.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
            case 'M': return date.getMonth() + 1;
            case 'MM': return zeroize(date.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
            case 'yy': return new String(date.getFullYear()).substr(2);
            case 'yyyy': return date.getFullYear();
            case 'h': return date.getHours() % 12 || 12;
            case 'hh': return zeroize(date.getHours() % 12 || 12);
            case 'H': return date.getHours();
            case 'HH': return zeroize(date.getHours());
            case 'm': return date.getMinutes();
            case 'mm': return zeroize(date.getMinutes());
            case 's': return date.getSeconds();
            case 'ss': return zeroize(date.getSeconds());
            case 'l': return date.getMilliseconds();
            case 'll': return zeroize(date.getMilliseconds());
            case 'tt': return date.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return date.getHours() < 12 ? 'AM' : 'PM';
        }
    });
};


function returnPage(pageId,direction, animate, speed, fun) {
    var Width = $("#" + pageId).width();
    var Height = $("#" + pageId).height();
    var BodyWidth = $("body").width();
    var BodyHeight = $("body").height();
    var Top = 0;
    var Left = 0;
    switch (direction) {
        case 'Up':
            Top = -1 * Height;
            Left = 0;
            break
        case 'Down':
            Top = BodyHeight;
            Left = 0;
            break
        case 'Left':
            Top = BodyHeight - Height;
            Left = -1 * Width;
            break
        case 'Right':
            Top = BodyHeight - Height;
            Left = BodyWidth;
            break
    }
    if (animate) {
        speed = speed ? speed : 'fast';
        $('#' + pageId).animate({'top':0 + 'px', 'left':Left + 'px'}, speed, function () {
            if (fun)fun.call(this);
        });
    } else {
        $('#' + pageId).css({'top':0 + 'px', 'left':Left + 'px'});
    }
    $("#" + pageId).hide();

}
function showPage(page, direction, animate, speed, fun){
    var Width = $("#" + page).width();
    var Height = $("#" + page).height();
    if($("#" + page).css('border')){
        try{
            Height += parseInt($("#" + page).css('border'),10);
        } catch (e){
        }
    }else if($("#" + page).css('border-top')){
        try{
            Height += parseInt($("#" + page).css('border-top'),10);
        } catch (e){
        }
    }
    var BodyWidth = $("body").width();
    var BodyHeight = $("body").height();
    var Top = BodyHeight - Height;
    var Left = 0;
    switch (direction) {
        case 'Up':
            $("#" + page).css({'top':BodyHeight + 'px', 'left':'0px'});
            break;
        case 'Down':
            $("#" + page).css({'top':(-1 * Height) + 'px', 'left':'0px'});
            break;
        case 'Left':
            $("#" + page).css({'top':0 + 'px', 'left':(BodyWidth) + 'px'});
            break;
        case 'Right':
            $("#" + page).css({'top':0 + 'px', 'left':(-1 * Width) + 'px'});
            break;
    }
    $('#'+page).css('display','block');
    if (animate) {
        speed = speed ? speed : 'fast';
        $('#'+page).animate({'top':0+'px','left':Left+'px'},speed,function(){
            if(fun)fun();
        });
    } else{
        $('#'+page).css({'top':0+'px','left':Left+'px'});
    }
};

/**
* 图片加载
* imgLi 图片对象集合
*/
function loadImg(imgLi,bg){
    if(imgLi && imgLi.length>0){
        for (var i = 0; i < imgLi.length; i++){
            var theImg = imgLi[i];
            if(theImg.getAttribute('url')!=''&&theImg.getAttribute('url')!='undefined'){
                var theUrl=theImg.getAttribute('url');
                imgReady(theImg,theUrl,function(){},function(imgs,width,heights){// 加载完成事件
                },function(){
                    theImg.src=bg;
                    console.log("图片加载错误");
                });
            }else{
                theImg.src=bg;
                console.log("没有图片地址");
            }
        }
    }else{
        console.log("需要加载的图片集合不存在~");
    }
};
function clone(jsonObj) {
    var  buf;
    if  (jsonObj  instanceof  Array) {
        buf = [];
        var  i = jsonObj.length;
        while  (i--) {
            buf[i] = clone(jsonObj[i]);
        }
        return  buf;
    }else   if  (jsonObj  instanceof  Object){
        buf = {};
        for  ( var  k  in  jsonObj) {
            buf[k] = clone(jsonObj[k]);
        }
        return  buf;
    }else {
        return  jsonObj;
    }
};
function consoleLog(msg,type){
    var time = new Date();
    if(!type){
        type = Log.Info.type;
    }
    switch(type){
        case Log.Info.type:
            console.log(time.format('yyyy-mm-dd hh:mm:ss:ll')+' '+Log.Info.prefix + msg);
            break;
        case Log.Debug.type:
            console.log(time.format('yyyy-mm-dd hh:mm:ss:ll')+' '+Log.Debug.prefix + msg);
            break;
        case Log.Error.type:
            console.log(time.format('yyyy-mm-dd hh:mm:ss:ll')+' '+Log.Error.prefix + msg);
            break;
    };

};
function isEmpty(obj){
    if(typeof obj === 'undefined' || obj == null || obj == 'undefined' || obj == 'null' || obj == ''){
        return true;
    }
    return false;
}